package com.aaa.ssm.controller;

import com.aaa.ssm.result.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class FileController {

    @Value("${haha.baseurl}")
    private  String BASE_URL ;
    @Value("${haha.dir}")
    private  String STORE_DIR ;
    @PostMapping
    public AjaxResult upload(MultipartFile file) {
        if (file.isEmpty()) {
            return  AjaxResult.error(400,"文件为空");
        }
        // 目标路径
        try {
            // 生成随机文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String randomFileName = UUID.randomUUID().toString() + fileExtension;
            String filePath=STORE_DIR+randomFileName;
            File dest = new File(filePath);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            //使用fileCopyUtils.copy()方法实现文件复制
            FileCopyUtils.copy(file.getInputStream(),new java.io.FileOutputStream(dest));
            String accessUrl=BASE_URL+randomFileName;
            return AjaxResult.success(accessUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return  AjaxResult.error(500,"文件上传失败");
        }
    }
}
